# -*- coding: utf-8 -*-
#
# File: setuphandlers.py
#
# Copyright (c) 2008 by ['JC Brand']
# Generator: ArchGenXML Version 2.0
#            http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#

__author__ = """JC Brand <jc@upfrontsystems.co.za>"""
__docformat__ = 'plaintext'


import logging
logger = logging.getLogger('mycrew: setuphandlers')
from Products.mycrew.config import PROJECTNAME
from Products.mycrew.config import DEPENDENCIES
import os
from Products.CMFCore.utils import getToolByName
import transaction
##code-section HEAD
from StringIO import StringIO
from Products.Archetypes.utils import shasattr
from Products.ATContentTypes.lib.constraintypes import ENABLED
from Products.CMFCore.WorkflowTool import WorkflowException
from Products.CMFCore.permissions import AddPortalContent, ListFolderContents
##/code-section HEAD

def isNotmycrewProfile(context):
    return context.readDataFile("mycrew_marker.txt") is None



def updateRoleMappings(context):
    """after workflow changed update the roles mapping. this is like pressing
    the button 'Update Security Setting' and portal_workflow"""
    if isNotmycrewProfile(context): return 
    shortContext = context._profile_path.split(os.path.sep)[-3]
    if shortContext != 'mycrew': # avoid infinite recursions
        return
    wft = getToolByName(context.getSite(), 'portal_workflow')
    wft.updateRoleMappings()

def postInstall(context):
    """Called as at the end of the setup process. """
    # the right place for your custom code
    if isNotmycrewProfile(context): return
    shortContext = context._profile_path.split(os.path.sep)[-3]
    if shortContext != 'mycrew': # avoid infinite recursions
        return
    site = context.getSite()
    setupGroupsAndRoles(site)
    publishFolders(site)
    allowMemberCreateForJobOfferFolder(site)
    setAddableTypes(site)



##code-section FOOT
def setupGroupsAndRoles(portal):
    # add roles
    for role in ['StaffMember']:
        if role not in portal.acl_users.portal_role_manager.listRoleIds():
            portal.acl_users.portal_role_manager.addRole(role)

    # Create groups
    portal_groups = portal.portal_groups
    if 'staff' not in portal_groups.listGroupIds():
        portal_groups.addGroup('Staff',
            roles=['Member', 'StaffMember'])

def publishFolders(portal):
    for id in ['collections', 'job-offers']:
        if shasattr(portal, id):
            obj = getattr(portal, id)
            try:
                portal.portal_workflow.doActionFor(obj, 'publish')
            except WorkflowException, e:
                logger.error('publishFolders: could not publish %s\n %s' \
                            % (id, e)) 
        else:
            logger.warn('publishFolders: %s folder does not exist!' % id)

def allowMemberCreateForJobOfferFolder(portal):
    for folder_id, roles, permission in \
                        [('job-offers', ('Member',), AddPortalContent), 
                         ('collections', ('StaffMember',), ListFolderContents)]:

        if shasattr(portal, folder_id):
            jofolder = getattr(portal, folder_id)
            jofolder.manage_permission(permission, 
                                    roles=roles, 
                                    acquire=1)
        else:
            logger.warn('allowMemberCreateForJobOfferFolder: %s folder \
                        does not exist!' % folder_id)

        
def setAddableTypes(site):
    wf = site.portal_workflow
    for folder_id, child_types in [('collections',('Topic',)), 
                                  ]:
        if type(folder_id) == tuple:
            parent = getattr(site, folder_id[0])
            i = 1
            while parent.getId() != folder_id[-2]:
                parent = getattr(parent, folder_id[i])
                i += 1

            folder = getattr(parent, folder_id[-1])
        else:
            folder = getattr(site, folder_id)

        folder.setConstrainTypesMode(ENABLED)
        folder.setLocallyAllowedTypes(child_types)
        folder.setImmediatelyAddableTypes(child_types)
##/code-section FOOT
